import { Modal, Button, Form, InputNumber, Select, message,Row,Col, Table} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import StockInput from './stockInput';

const FormItem = Form.Item;
const Option = Select.Option;
function hasErrors(fieldsError) {
    let error = Object.keys(fieldsError).some(field => fieldsError[field]);
    return error;
}

@Form.create()
class ChangeStock extends React.Component {

    constructor(props) {
        super(props);
        this.state= {
            columns: [],
            btnLoading: false
        }
    }

    handleOk = () => {
        const { _thisInSale, _thisInStock,_thisSoldOut } = this.props;
        const _this = _thisInSale|| _thisInStock||_thisSoldOut;
        _this.setState({ editStockVisible: false }, () => {
            this.forceUpdate();
        });
    };

    handleCancel = () => {
        const { _thisInSale, _thisInStock,_thisSoldOut } = this.props;
        const _this = _thisInSale|| _thisInStock||_thisSoldOut;
        _this.setState({ editStockVisible: false }, () => {
            this.forceUpdate();
        });
    };

    componentWillMount() {
        window.Isoption = false;
      }
      componentDidMount() {
        window.Isoption = true;
      }

       // 取消
       clickCancel =() => {
        this.setState({
            allValue: '',
        })
        this.handleCancel();
    }

    // 确认
    changePriceBtn =() => {
        this.props.form.validateFields((err, values) =>{
            if(!err) {
                const {  _thisInSale, _thisInStock,_thisSoldOut,dispatch, ProductId, sourceDatas} = this.props;
                const ProductSku = [];
                this.setState({
                  btnLoading: true
              })
                sourceDatas.map((item, index) => {
                    ProductSku.push({
                        SkuId: item.skuId,
                        StockNum: item.stock_num
                    })
                    return ProductSku;
                })
                dispatch({
                    type: 'pruductSellList/UpdateProductStock',
                    payload: {
                        ProductId: ProductId,
                        ProductSku: ProductSku
                    },
                    callBack: {
                        success: res => {
                          if (res.Code === 0) {
                            message.success('修改成功');
                            this.handleOk();
                            if(_thisInSale) {
                                this.props._thisInSale.GetSellProductList();
                            }
                            if(_thisInStock) {
                                this.props._thisInStock.getSearchWarehouseProductListWithPage();
                            }
                            if(_thisSoldOut) {
                                this.props._thisSoldOut.getSearchSoldOutProductListWithPage();
                            }
                            this.setState({
                                allValue: '',
                                btnLoading: false
                            })
                          }
                        },
                        error: res => {
                          message.error(res.Msg);
                          this.setState({ btnLoading: false });
                        },
                    },
                })
            }
        })
    }

    getAllInputValue =(value, data) => {
        this.setState({
            allValue: value,
        })
    }

    getInputValue =(e, value, data, index) => {
    const {dispatch, sourceDatas} = this.props;
    sourceDatas[index].stock_num = e;
    dispatch({
        type:'pruductSellList/changeData',
        payload:sourceDatas,
        callBack:{
            success:(res)=>{
                this.forceUpdate();
            }
        }
    })
  }

    // 保存
    clickSetOnTime =() => {
        this.props.form.validateFields((error) =>{
            if(!error) {
                const { allValue} = this.state;
                const {sourceDatas,dispatch} = this.props;
                sourceDatas.map((item, index) => {
                    item.stock_num = allValue
                })
                dispatch({
                    type:'pruductSellList/changeData',
                    payload:sourceDatas,
                    callBack:{
                        success:(res)=>{
                            this.forceUpdate();
                        }
                    }
                })
            }
        })
    }

    checkBlur = (id) => {
        this.props.form.validateFields([id], { force: true });
      }

    render() {
        const {editStockVisible, _this, productSkuInfo, ProductId,sourceDatas} = this.props;
        const {getFieldDecorator} = this.props.form;
        const {btnLoading} = this.state;
        const formItemLayout = {
          labelCol: {
            span: 4 ,
          },
          wrapperCol: {
            span: 8 ,
          },
        };

        //
        const data = sourceDatas;
        let skuList=[];
        let rex1=/^k[0-9]*$/gi;
        if (data&&data.length> 0) {
            Object.keys(data[0]).forEach(function(key){
                if(key.match(rex1))
                {
                    var sid=key.replace("k","");
                    let item={ id:data[0]["k"+sid+"_id"],name:data[0][key] };
                    skuList.push(item);
                }
           });
        }
        skuList.push(
            { id:0, name:'库存' }
        );

        let arr = [], obj = {};

        let g1=0;
        let g2=0;
        let g3=0;
        const columns = [];

        skuList.forEach((item,itemIndex)=>{
            let dataIndex="v1";
            let width = 0;
            let align = '';
            if (skuList.length=== 4) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = '25%';
                }
                if(itemIndex===1){
                    dataIndex="v2";
                    width = '25%';
                }
                if(itemIndex===2){
                    dataIndex="v3";
                    width = '25%';
                }
                if (itemIndex===3){
                    dataIndex="stock_num";
                    width = 100;
                }
             } if (skuList.length=== 3) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = '35%';
                }
                if(itemIndex===1){
                    dataIndex="v2";
                    width = '35%';
                }
               if (itemIndex===2){
                    dataIndex="stock_num";
                    width = '30%';
                }
             }if (skuList.length=== 2) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = '40%';
                }
                if (itemIndex===1){
                    dataIndex="price";
                    width = '20%';
                }
               }

            let col={
                title: item.name,
                dataIndex: dataIndex,
                width:  width,
                align: 'left',
                render: (text, row, index) => {
                    const obj = {
                        children: text,
                        props: {},
                    };
                  if (skuList.length=== 4) {
                    if(itemIndex===0){
                        if(row.v1_id!==g1){
                            obj.props.rowSpan = row.row_1_num;
                            g1=row.v1_id;
                            g2=0;
                            g3=0;
                        }
                        else{
                            obj.props.rowSpan=0;
                        }
                     }
                    if(itemIndex===1) {
                        if(row.v2_id!==g2){
                            obj.props.rowSpan = row.row_2_num;
                            g2=row.v2_id;
                            g3=0;
                        }else{
                            obj.props.rowSpan=0;
                        }
                     }
                    if(itemIndex===2) {
                        if(row.v3_id!==g3){
                            obj.props.rowSpan = row.row_3_num;
                            g3=row.v3_id;
                        }else{
                            obj.props.rowSpan=0;
                        }
                     }
                     if (itemIndex===3){
                        return (
                            <FormItem>
                               {this.props.form.getFieldDecorator('stock_num' + index, {
                                    initialValue: data[index].stock_num,
                                    rules: [
                                        {required: true,message: `请输入库存`},
                                        {pattern: /^([1-9]\d*|[0]{1,1})$/, message: '不小于0整数'}
                                    ]
                                 })(
                                <StockInput
                                    setValue={data[index].stock_num}
                                    onChange={e => this.getInputValue(e,row,data,index)}
                                    min={0}
                                    max={999999}
                                    style={{width: '100%'}}
                                    onBlur={() => { this.checkBlur('stock_num' + index) }}
                              />
                              )}
                            </FormItem>
                        )
                     }
                  } if (skuList.length=== 3) {
                    if(itemIndex===0){
                        if(row.v1_id!==g1){
                            obj.props.rowSpan = row.row_1_num;
                            g1=row.v1_id;
                            g2=0;
                            g3=0;
                        }
                        else{
                            obj.props.rowSpan=0;
                        }
                     }
                     if(itemIndex===1) {
                        if(row.v2_id!==g2){
                            obj.props.rowSpan = row.row_2_num;
                            g2=row.v2_id;
                            g3=0;
                        }else{
                            obj.props.rowSpan=0;
                        }
                     }
                     if (itemIndex===2){
                        return (
                            <FormItem>
                                {this.props.form.getFieldDecorator('stock_num' + index, {
                                    initialValue: data[index].stock_num,
                                    rules: [
                                        {required: true,message: `请输入库存`},
                                        {pattern: /^([1-9]\d*|[0]{1,1})$/, message: '不小于0整数'}
                                    ]
                                })(
                                <StockInput
                                    setValue={data[index].stock_num}
                                    onChange={e => this.getInputValue(e,row,data,index)}
                                    min={0}
                                    max={999999}
                                    style={{width: '100%'}}
                                    onBlur={() => { this.checkBlur('stock_num' + index) }}
                            />
                            )}
                         </FormItem>
                        )
                     }
                  } if (skuList.length=== 2) {
                    if(itemIndex===0){
                        if(row.v1_id!==g1){
                            obj.props.rowSpan = row.row_1_num;
                            g1=row.v1_id;
                        }
                        else{
                            obj.props.rowSpan=0;
                        }
                     }
                     if (itemIndex===1){
                        return (
                            <FormItem>
                                {this.props.form.getFieldDecorator('stock_num' + index, {
                                    initialValue: data[index].stock_num,
                                    rules: [
                                        {required: true,message: `请输入库存`},
                                        {pattern: /^([1-9]\d*|[0]{1,1})$/, message: '不小于0整数'}
                                    ]
                                })(
                                <StockInput
                                    setValue={data[index].stock_num}
                                    onChange={e => this.getInputValue(e,row,data,index)}
                                    min={0}
                                    max={999999}
                                    style={{width: '100%'}}
                                    onBlur={() => { this.checkBlur('stock_num' + index) }}
                            />
                            )}
                         </FormItem>
                        )
                     }
                }
                  return obj;
                },
            }
            columns.push(col)
        })


        return (
            <div>
                <Modal
                    visible={editStockVisible}
                    title="修改库存"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    footer={null}
                    width={640}
                    className={styles.form}
                >
                    <div className={styles.modalTableContent}>
                        <Table
                            bordered
                            dataSource={sourceDatas}
                            pagination={false}
                            columns={columns}
                            rowKey ={(record) => record.id}
                            className={styles.tableBox}
                        />
                    </div>
                          <div className={styles.footerLine}>
                            <FormItem label="批量设置" {...formItemLayout}>
                                {getFieldDecorator('numbers', {
                                        rules: [
                                        {required: false, message: ''},
                                        {pattern: /^([1-9]\d*|[0]{1,1})$/, message: '不小于0整数'}
                                    ]
                                })(
                                    <span className={styles.inputBox}>
                                        <InputNumber
                                            placeholder="请填写库存"
                                            min={0} max={999999}
                                            value={this.state.allValue}
                                            onChange={e => this.getAllInputValue(e, sourceDatas)}
                                        />
                                        <a
                                        href="javascript:;"
                                        style={{width: '3em', marginLeft: 8}}
                                        onClick={() => this.clickSetOnTime()}>
                                            保存
                                        </a>
                                    </span>
                                )}
                            </FormItem>
                            <div>
                                <Button onClick={this.clickCancel}>取消</Button>
                                <Button
                                  type="primary"
                                  style={{marginLeft: 8}}
                                  onClick ={this.changePriceBtn}
                                  loading={btnLoading}
                                >确认</Button>
                            </div>
                        </div>
                </Modal>
            </div>
        )
    }
}

export default connect(({productSkuInfo, pruductSellList,global, loading}) => ({
    productSkuInfo,
    sourceDatas:pruductSellList.sourceData
}))(ChangeStock)
